package com.itheima.tlias.service.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.pojo.Emp;
import com.itheima.tlias.pojo.EmpExpr;
import com.itheima.tlias.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service("EmpServiceImpl")
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;

    @Override
    public List<Emp> findAll() {
        return empMapper.findAll();
    }

    @Override
    public List<Emp> findSomeEmp(Emp emp, Date begin, Date end, int page, int pageSize) {
        // 使用 PageHelper 进行分页
        PageHelper.startPage(page, pageSize);
        return empMapper.findSomeEmp(emp, begin, end);

    }

    @Override
    public int delete(Integer... id) {
        int delete = empMapper.delete(id);
        int deleteEmpExpr = empMapper.deleteEmpExpr(id);
        if (deleteEmpExpr > 0 && delete > 0)
        return 1;
        return 0;
    }

    @Override
    public int insert(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        int insert = empMapper.insert(emp);
        for (EmpExpr expr : emp.getExprList()) {
            expr.setEmpId(emp.getId());
        }
        empMapper.insertEmpExpr(emp.getExprList());
        return Math.max(insert, 0);
    }

    @Override
    public Emp findById(Integer id) {
        if (id > 0){
            Emp emp = empMapper.findById(id);
            List<EmpExpr> empExprById = empMapper.findEmpExprById(id);
            emp.setExprList(empExprById);
            return emp;
        }
        return null;
    }

    @Override
    public int update(Emp emp) {
        if (emp.getId() > 0){
            // 更新时间
            emp.setUpdateTime(LocalDateTime.now());
            int update = empMapper.update(emp);
            // 删除老的
            empMapper.deleteEmpExpr(new Integer[]{emp.getId()});
            for (EmpExpr expr : emp.getExprList()) {
                expr.setEmpId(emp.getId());
            }
            // 插入新的
            empMapper.insertEmpExpr(emp.getExprList());
            return update;
        }
        return 0;
    }
}
